import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { AwardService } from 'src/award/award.service';
import { UserService } from 'src/user/user.service';
import {
  DynamicItem,
  dynamicModel,
  Dynamics,
  tagModel,
} from './entities/dynamic.entity';

@Injectable()
export class DynamicService {
  async addDynamic(
    openid: string,
    awardId: string,
    article: string,
    background: string,
  ) {
    const awardService = new AwardService();
    const award = await awardService.findItemById(openid, awardId);
    if (!award) {
      throw new HttpException(
        {
          message: '奖励列表没有该奖励',
          success: false,
        },
        HttpStatus.BAD_REQUEST,
      );
    }
    const { tags: tagnames, tomato } = award;
    const userService = new UserService();
    const user = await userService.getProfile(openid);

    const dynamicItem: DynamicItem = {
      openid,
      author: user.nickname,
      head_image: user.head_image,
      article,
      tomato,
      background,
    };
    const dynamics: Dynamics = {
      tagnames,
      ...dynamicItem,
    };
    await dynamicModel.insertOne(dynamics);
    for (const tagname of tagnames) {
      await tagModel.updateOne(
        { tagname },
        { $push: { dynamics: dynamicItem } },
      );
    }
  }

  async getDynamics(page: number, page_size: number) {
    const data = await dynamicModel.find<Dynamics>(
      {},
      {
        sort: [['_id', -1]],
        skip: page * page_size,
        limit: page_size,
      },
    );
    return data;
  }
}
